<?php
namespace app\widget\controller;
use app\common\controller\AdminBase;

class ApiAdminWidgetMod extends AdminBase
{
    public function install()
    {
       $name = input('post.name');
       if (!$name) {
           return jsonError('缺少参数');
       }
       $itemInfo = db('WidgetMod')->where('name',$name)->find();
       if ($itemInfo) {
           return jsonError('该模块已安装，无法再次安装');
       }
       $class = 'app\\' . $name .'\\' . ucfirst($name);
       $app = new $class();
       if (!$app->install()) {
           return jsonError('执行模块预安装操作失败');
       }
       $sqlFile = ROOT_PATH . 'app' . DS . $name . DS . 'install.sql';
       if (is_file($sqlFile)) {
           try {
               $hostname = config('database.hostname');
               $database = config('database.database');
               $hostport = config('database.hostport');
               $username = config('database.username');
               $password = config('database.password');
               $dsn = "mysql:dbname={$database};host={$hostname};port={$hostport};charset=utf8";
               try {
                   $db = new \PDO($dsn, $username, $password);
               } catch (\PDOException $e) {
                   return jsonError('错误代码:'.$e->getMessage());
               }
               $prefix = config('database.prefix');
               $sql = file_get_contents($sqlFile);
               $sql = str_replace("\r", "\n", $sql);
               $sql = explode(";\n", $sql);
               foreach ($sql as $item) {
                   $item = trim($item);
                   if (empty($item)) continue;
                   preg_match('/CREATE TABLE `([^ ]*)`/', $item, $matches);
                   if ($matches) {
                       if (false !== $db->exec($item)) {
                       } else {
                          return jsonError('安装失败');
                       }
                   } else {
                       $db->exec($item);
                   }
               }
           } catch (\PDOException $e) {
               return jsonError('数据库安装失败，原因：' . $e);
           }
       }
       $info = $app->info;
       db('WidgetMod')->insert(array(
           'name' => $info['name'],
           'title' => $info['title'],
           'description' => $info['description'],
           'author' => $info['author'],
           'status' => $info['status'],
           'version' => $info['version'],
           'is_admin' => $info['adminUrl'] ? 1 : 0,
           'add_time' => time(),
           'is_global' => $info['isGlobalAction'] ? 1 : 0,
       ));
       return jsonSuccess('ok');
    }

    public function uninstall()
    {
       $id = input ('id');
       if (!$id) {
           return jsonError('缺少参数');
       }
       $itemInfo = db('WidgetMod')->where('id',$id)->find();
       if (!$itemInfo) {
           return jsonError('卸载项不存在');
       }
       $name = $itemInfo['name'];
       try {
           $class = 'app\\' . $name .'\\' . ucfirst($name);
           $app = new $class();
           if (!$app->uninstall()) {
               return jsonError('执行插件预卸载操作失败');
           }
       } catch (\Exception $e) {
        
       }
       db('WidgetMod')->where('id',$id)->delete();
       $sqlFile = ROOT_PATH . 'app' . DS . $itemInfo['name'] . DS . 'uninstall.sql';
       if (is_file($sqlFile)) {
           try {
               $hostname = config('database.hostname');
               $database = config('database.database');
               $hostport = config('database.hostport');
               $username = config('database.username');
               $password = config('database.password');
               $dsn = "mysql:dbname={$database};host={$hostname};port={$hostport};charset=utf8";
               try {
                   $db = new \PDO($dsn, $username, $password);
               } catch (\PDOException $e) {
                   return jsonError('错误代码:'.$e->getMessage());
               }
               $prefix = config('database.prefix');
               $sql = file_get_contents($sqlFile);
               $sql = str_replace("\r", "\n", $sql);
               $sql = explode(";\n", $sql);
               foreach ($sql as $item) {
                   $item = trim($item);
                   if (empty($item)) continue;
                   preg_match('/CREATE TABLE `([^ ]*)`/', $item, $matches);
                   if ($matches) {
                       if (false !== $db->exec($item)) {
                       } else {
                          return jsonError('卸载失败');
                       }
                   } else {
                       $db->exec($item);
                   }
               }
           } catch (\PDOException $e) {
               return jsonError('数据库卸载失败，原因：' . $e);
           }
       }
       return jsonSuccess('ok');
    }
    
    public function itemList()
    {
        $appPath = ROOT_PATH . 'app' . DS;
        $templateDir = opendir($appPath);
        if ($templateDir) {
            while (false !== ($file = readdir($templateDir))) {
                if (substr($file, 0, 1) != '.' AND is_dir($appPath . $file)) {
                    $dirs[] = $file;
                }
            }
            closedir($templateDir);
        }
        $app = array();
        $tempAddons = array();
        $tempAddons = array();
        if ($dirs) {
            foreach ($dirs as $val) {
                $classFile = APP_PATH . $val . DS . ucfirst($val) . '.php';
                $sqlFile = APP_PATH . $val . DS . 'install.sql';
                if (is_file($sqlFile)) {
                    $item = db('WidgetMod')->where('name',$val)->find();
                    if ($item) {
                        $item['istall'] = 1;
                        $app[$val] = $item;
                    } else {
                        $class = 'app\\' . $val .'\\' . ucfirst($val);
                        if (!class_exists($class)) {
                            continue;
                        }
                        $obj = new $class();
                        $app[$val] = $obj->info;
                        $app[$val]['istall'] = 0;
                    }
                    $tempAddons[] = $app[$val];
                }
            }
        }
        return jsonSuccess('',array('itemList' => $tempAddons));
    }
    
}